#include"TcpServer.hpp"
#include<memory>
#include"Log.hpp"
#include"Calculator.hpp"
#include"Protocol.hpp"
#include<functional>
#include"Daemon.hpp"

using namespace LogModule;

using Cal_t = std::function<Response(const Request& req)>;

// using cal_fun = std::function<Response(const Request &req)>;

// // package一定会有完整的报文吗？？不一定把
// // 不完整->继续读
// // 完整-> 提取 -> 反序列化 -> Request -> 计算模块，进行处理

class Parse
{
    public:
    Parse(Cal_t cal)
    :_cal(cal)
    {

    }
    std::string Entry(std::string& package)
    {
        std::string message;
        std::string resptr;
        while(Decode(package,&message))
        {
            LOG(LogLevel::DEBUG) << "Content: \n" << message;
            if(message.empty())
            break;
            //反序列化
            Request req;
            if(!req.deserialize(message))
            break;

            //计算
            std::string tmp;
            Response resp = _cal(req);
            resp.Serialize(tmp);

            //添加长度字段
            Encode(tmp);

            //拼接应答，这样的话有多少个需求都会处理，最后统一返回
            resptr+=tmp;

        }
        return resptr;
    }
    private:
    Cal_t _cal;
};

int main()
{
    //ENABLE_FILE_LOG();

    //Daemon(false,false);
    Cal cal;
    Parse parse([&cal](const Request& req){
        return cal.entry(req);
    });
    
    std::shared_ptr<TcpServer> tserver = std::make_shared<TcpServer>([&parse](std::string &package){
       return parse.Entry(package);
    });
    tserver->InitServer();
    tserver->Start();


    return 0;
}